/* 
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

// 默认子tab
var defaultTabIndex = 1;

// 群发封面URI
var groupImageURI = false;

// 编辑器加载标记
var ueloaded = false;

// 编辑器加载标记2
var ueploaded = false;

// 目前cardIndex
var currentCard = 0;

var currentPage = false;

// 是否在首页
var is_adminhome = false;

// 订单列表onload
var orderListloaded = false;

// 默认card Index
var defaultCard = 1;

// 登录二维码过期
var qrcode_exps = 300;

// 群发固定高度
var groupSendHeight = 413;

// 商品编辑固定高度
var productEditHeight = 480;

var stdHeight = document.documentElement.clientHeight - 40;

var defaultPage = 'list_products';

var currentSubnav = '';

// jq lis
$(function() {
    // 导航按钮效果
    $('.navItem').click(function() {
        $('.navItem.hover').removeClass('hover');
        $(this).toggleClass('hover');
    });

    if ($('.wdmin-main').length > 0) {
        is_adminhome = true;
        $('#navitem5').click();
    }
    
    $('#right_iframe').on('load', function() {
        window.setTimeout(function() {
            $('#iframe_loading').fadeOut();
        }, 500);
    });

    // resize
    window.onresize = __resize__;
    __resize__();
});

/**
 * window resizing lis
 * @returns {undefined}
 */
function __resize__() {
    stdHeight = document.documentElement.clientHeight - 40;
    $('.wdmin-login').height(stdHeight + 'px');
    $('.wdmin-main,#rightWrapper').css('height', stdHeight + 'px');
    $('#main-mid,#main-mid-left,#main-mid-right,#wdmin-wrap').css('height', stdHeight + 'px');
    $('#wdmin-wrap').css('margin-top', (document.documentElement.clientHeight - $('#wdmin-wrap').height()) / 2 + 'px');
    $('#right_iframe').css('height', stdHeight - 43 + 'px');
    $('.card-subtab').css('min-height', stdHeight - 43 + 'px');
    absmid('#qrcode-login-wrapp');
    // productlist resize
    (function() {
        var h = $('.wd-productlist').width();
        $('.wd-productlist').each(function(i, node) {
            $(node).height(h);
        });
        h = null;
    })();
    if (ueloaded) {
        ue.setHeight(document.documentElement.clientHeight - groupSendHeight);
    }
    if (ueploaded) {
        uep.setHeight(document.documentElement.clientHeight - productEditHeight);
    }
    $('.card-subtab.resize').css('height', stdHeight - 75 + 'px');
    $('.pageNot').each(function(i, node) {
        $(node).css('line-height', $(node).height() + 'px');
    });
    $('#cos-left,#cos-right').height(stdHeight - 43);
}

/**
 * switchCard
 * @param {type} cardId
 * @returns {undefined}
 */
function switchCard(cardId) {
    currentCard = cardId;
    var card = $('#card' + cardId);
    // var btn = $('#navitem' + cardId);
    $('._card').removeClass('_show');
    // load card 
    if (!card.hasClass('loaded')) {
        wpLoading();
        $.get('views/wdmin/card/card' + cardId + '.php', function(r) {
            // load javaScript
            $('#card' + cardId).append(r);
            $.getScript('static/wdmin/script/card' + cardId + '.js', function() {
                subTabSwitch();
                __resize__();
                __resize__();
            });
            card.addClass('loaded');
        });
    } else {
        subTabSwitch();
    }
    card.addClass('_show');
    loadStatData();
    __resize__();
    __resize__();
}

/**
 * 
 * @param {String} page
 * @param {String} nav
 * @returns {Boolean}
 */
function loadPage(page, nav) {
    if (this !== window) {
        page = $(this).attr('data-page');
        nav = $(this).attr('data-nav');
    }
    if (currentPage !== page) {
        // 加载导航
        if (currentSubnav === '' || currentSubnav !== nav) {
            $('#__subnav__').load('/views/wdminpage/subnavs/subnav_' + nav + '.php', function() {
                $('.cap-nav-item').unbind('click').click(loadPage);
                $('.cap-nav-item').eq(0).addClass('cur');
                currentSubnav = nav;
            });
        } else {
            // 按钮状态切换
            $('.cap-nav-item.cur').removeClass('cur');
            $(this).addClass('cur');
        }
        // 加载页面
        $('#iframe_loading').fadeIn();
        $('#right_iframe').attr('src', '?/WdminPage/' + page);
        currentPage = page;
        return true;
    }
}

/**
 * 
 * @param {type} __callback
 * @param {type} tabId
 * @returns {undefined}
 */
function subTabSwitch(tabId, __callback) {
    tabId = tabId || defaultTabIndex;
    var subTab = $('#card' + currentCard + '-subtab' + tabId);
    var subTabBtn = $('#card' + currentCard).find('.cap-nav-item').eq(tabId - 1);
    $('.card-subtab').hide();
    subTab.show();
    subTab = null;
    if (!subTabBtn.hasClass('cur')) {
        $('.cap-nav-item.cur').removeClass('cur');
        subTabBtn.addClass('cur');
        __resize__();
    }
    // tabonload func call
    try {
        eval('c' + currentCard + 'tab' + tabId + 'onload(__callback)');
    } catch (e) {
        console.log(e);
    }
    $('#main-mid').scrollTop(0);
}

/**
 * loadStatData
 * @returns {undefined}
 */
function loadStatData() {
    $.get('?/Wdmin/ajaxGetOrderCount', function(r) {
        $('#stat-ordercount').html(r);
    });
}

// 加载gif提示
function wpLoading(id) {
    id = id || "#main-mid";
    Loading.start(id);
}

/**
 * 
 * @param {type} url
 * @param {type} title
 * @param {type} desc
 * @param {type} catimg
 * @returns {undefined}
 */
function gmessSend(url, title, desc, catimg, msgid) {

    var request_uri = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=';

    // 获取关注者列表
    $.get('?/WdminAjax/ajaxGetSubScribelist', function(res) {
        var successCount = 0;
        var oSlist = res.toJson();
        request_uri += oSlist.accesstoken;
        subTabSwitch(4);

        function _send(i) {
            // 参数
            var postData = {
                touser: oSlist.data.openid[i],
                msgtype: 'news',
                news: {
                    articles: [
                        {
                            title: encodeURI(title),
                            description: encodeURI(desc),
                            url: encodeURI(url),
                            picurl: decodeURI(catimg)
                        }
                    ]
                }
            };
            $.post(shoproot + '_proxy/post.php', {
                url: request_uri,
                postdata: postData,
                mod: 1
            }, function(res) {
                res = res.toJson();
                if (0 === parseInt(res.errcode)) {
                    // 群发到达
                    successCount++;
                }
                groupSendProcessing(((i++) / oSlist.total) * 100);
                if (oSlist.total === i) {
                    groupSendProcessing(100);
                    $.post('?/WdminAjax/UploadGroupSendStatData', {
                        msgid: msgid,
                        success: successCount,
                        total: oSlist.total
                    }, function(R) {
                        $('.cap-progress').hide();
                        $('#gmess-send-btn1').css('display', 'inline-block');
                        window.chsmsgid = false;
                        loadSendList();
                        subTabSwitch(2);
                        i = null;
                        return true;
                    });
                } else {
                    _send(i);
                }
            });
        }
        _send(0);
    });
}

/**
 * 发送进度提示
 * @param {type} percent
 * @returns {Boolean}
 */
function groupSendProcessing(percent) {

    if (percent > 100) {
        return false;
    }

    var nProgress = $('#card6-progress');
    var nProgressBar = nProgress.find('a');
    var nProgressBarCap = nProgress.find('b');

    if (percent === 0) {
        nProgress.css('margin-top', (nProgress.parent().height() / 2) + 'px');
        // nProgress.parent().css('height', 0);
    }

    nProgressBar.css('width', percent + '%');
    nProgressBarCap.html('消息正在发送中<br/>' + parseFloat(percent).toFixed(2) + '%');
    nProgress.show();
}

function loginCheck() {
    if ($('#pd-form-username').val() !== '' && $('#pd-form-password').val() !== '') {
        $.post(shoproot + '?/Wdmin/checkLogin/', {
            admin_acc: $('#pd-form-username').val(),
            admin_pwd: $('#pd-form-password').val()
        }, function(res) {
            res = res.toJson();
            if (parseInt(res.status) === 1) {
                $.cookie("loginKey", res.loginKey, {path: '/'});
                location.href = shoproot + '?/Wdmin/';
            } else {
                alert('登录失败，用户名或者密码错误！');
            }
        });
    }
}